/*
 * @Author: dadadaXU 1413107032@qq.com
 * @Date: 2025-01-30 20:14:31
 * @LastEditors: dadadaXU 1413107032@qq.com
 * @LastEditTime: 2025-01-30 20:33:51
 * @FilePath: \LeetCode\19.删除链表的倒数第-n-个结点.cpp
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
/*
 * @lc app=leetcode.cn id=19 lang=cpp
 *
 * [19] 删除链表的倒数第 N 个结点
 *
 * 方法1：双指针间隔为 n，且 n <= len
 */

struct ListNode
{
    int val;
    ListNode *next;
    ListNode() : val(0), next(nullptr) {}
    ListNode(int x) : val(x), next(nullptr) {}
    ListNode(int x, ListNode *next) : val(x), next(next) {}
};

// @lc code=start
class Solution
{
public:
    ListNode *removeNthFromEnd(ListNode *head, int n)
    {
        ListNode *p1 = head;
        for (int i = 0; i < n; i++)
            p1 = p1->next;

        if (p1 == nullptr) // 删除第一个结点
        {
            p1 = head;
            head = head->next;
            delete p1;
            return head;
        }

        ListNode *p2 = head;
        while (p1->next != nullptr)
        {
            p1 = p1->next;
            p2 = p2->next;
        }

        ListNode *del = p2->next;
        p2->next = del->next;
        delete del;

        return head;
    }
};
// @lc code=end
